<?php


/**
 * Function that encrypts the password when given one parameter and compares them when given two parameters
 * @param string $info
 * @param string $encdata
 * @return boolean|string
 */
function hasher($info, $encdata = false)
{
        $strength = "08";
        //if encrypted data is passed, check it against input ($info)
        if ($encdata) {
                if (substr($encdata, 0, 60) == crypt($info, "$2a$".$strength."$".substr($encdata, 60))) {
                        return true;
                }
                else {
                        return false;
                }
        }
        else {
                //make a salt and hash it with input, and add salt to end
                $salt = "";
                for ($i = 0; $i < 22; $i++) {
                        $salt .= substr("./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", mt_rand(0, 63), 1);
                }
                //return 82 char string (60 char hash & 22 char salt)
                $cry = crypt($info, "$2a$".$strength."$".$salt).$salt;
                return $cry;
        }
}

/**
 * Function that uses the characters from $valid_chars to create a random string with the length of $length
 * @param string $valid_chars
 * @param int $length
 * @return string
 */
function get_random_string($valid_chars, $length)
{
        // start with an empty random string
        $random_string = "";

        // count the number of chars in the valid chars string so we know how many choices we have
        $num_valid_chars = strlen($valid_chars);

        // repeat the steps until we've created a string of the right length
        for ($i = 0; $i < $length; $i++)
        {
                // pick a random number from 1 up to the number of valid chars
                $random_pick = mt_rand(1, $num_valid_chars);

                // take the random character out of the string of valid chars
                // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
                $random_char = $valid_chars[$random_pick-1];

                // add the randomly-chosen char onto the end of our string so far
                $random_string .= $random_char;
        }

        // return our finished random string
        return $random_string;
}


/**
 * Returns wether the given value is a valid int or not
 * @param mixed $value
 * @return mixed
 */
function check_for_int($value){
        if(preg_match("/^([0-9]{1,6})$/", $value)){
                $value = intval($value);
                // Check if page is below 0 (may not happen by programm itself)
                if($value<=0){
                        return false;
                } else {
                        return $value;
                }
        }else{
                return false;
        }
}
?>